package models;

import java.util.ArrayList;
import java.util.List;

import siena.Column;
import siena.Generator;
import siena.Id;
import siena.Model;
import siena.Query;
import siena.Table;

@Table("tag_reference")
public class TagReference extends Model {

	@Id(Generator.AUTO_INCREMENT)
	public Long id;
	@Column("entry_id")
	public Long entryId;
	@Column("tag_id")
	public Long tagId;
	
	public TagReference(Long entryId, Long tagId) {
		this.entryId = entryId;
		this.tagId = tagId;
	}
	
	public static List<Tag> getTags(Long entryId) {
		List<TagReference> refs = all().filter("entryId", entryId).fetch();
		List<Tag> tags = null;
		if(refs != null && !refs.isEmpty()) {
			tags = new ArrayList<Tag>(refs.size());
			for(TagReference ref : refs) {
				Tag tag = Tag.get(ref.tagId);
				tags.add(tag);
			}
		}
		return tags;
	}
	
	public static List<BlogEntry> getEntrys(Long tagId) {
		List<TagReference> refs = all().filter("tagId", tagId).fetch();
		List<BlogEntry> tags = null;
		if(refs != null && !refs.isEmpty()) {
			tags = new ArrayList<BlogEntry>(refs.size());
			for(TagReference ref : refs) {
				BlogEntry tag = BlogEntry.get(ref.entryId);
				tags.add(tag);
			}
		}
		return tags;
	}
	
	public static Query<TagReference> all() {
		return Model.all(TagReference.class);
	}
}
